#include "cluster_project.h"

int deleteHelper(LINK head);

int createNewList(LINK *p_list, DATA G)
{
	LINK head = NULL, tail = NULL;
	/*First we delete the previous list*/
	/*read the first char*/
	if (G != NULL)
	{
		head = (ELEMENT *)malloc(sizeof(ELEMENT));
		head->d = G;
		tail = head;
	}
	else/*The empty string*/
		return 1;
	/*Set the list's end*/
	tail->next = NULL;
	/*Set the list's head*/
	*p_list = head;
	return 1;
}

/* Recursive deletion of a list */
int deleteList(LINK *p_list)
{
	/*If the string is not the empty string delete it's elements*/
	if (*p_list!=NULL)
		deleteHelper(*p_list);
	/*Set the string to be the empty string*/
	*p_list=NULL;
	return 1;
}

/*The recursive helper method*/
int deleteHelper(LINK head)
{
	if (head->next != NULL)
	{
		deleteHelper(head->next);
	}
	head->next=NULL;
	freeNodesGroup(&(head->d));
	free(head);
	return 1;
}

int groups_compare (const void * a, const void * b){
	ELEMENT *ia = (ELEMENT *)a;
	ELEMENT *ib = (ELEMENT *)b;
	return ((ia->d->Group)[0] - (ib->d->Group)[0]);
}

/*Prints the all the groups in the list by asceding order according*/
/*to the first index of the group*/
int printList(LINK list, int iListSize, double deltaQ, char *path)
{
	int minIndex;
	int printedGroups = 0;
	LINK elem, head;
	int lastPrinted = -1;
	
	while (printedGroups < iListSize)
	{
		head = list;
		minIndex = MAX_INT;
		while (head != NULL)
		{
			if ((head->d->Group)[0] <= minIndex && (head->d->Group)[0] > lastPrinted)
			{
				minIndex = (head->d->Group)[0];
				elem = head;
			}
			head = head->next;
		}
		if (elem != NULL)
		{
			printIntVector(elem->d->Group, elem->d->iGroupSize, path, elem->d->grade, elem->d->numOfIter);
			lastPrinted = (elem->d->Group)[0];
			printedGroups++;
		}
	}
	return 1;
}


int removeFromList(LINK *p_list, DATA G)
{
	LINK temp;
	/*Pass through the list*/
	while(*p_list!=NULL)
	{
		if ((*p_list)->d==G)/*Found one!*/
		{
			temp=*p_list;
			*p_list=(*p_list)->next;
			free(temp);
			return 1;/*Can be only one instance of a group...*/
		}
		p_list=&((*p_list)->next);/*Advance*/
	}
	return 1;
}

int insertToList(LINK *p_list, DATA G)
{
	LINK newElem;

	if (G == NULL)
	{
		return 0;
	}

	/*If the list was never inited we'll create a new one*/
	if (*p_list == NULL)
	{
		return createNewList(p_list, G);
	}
	
	/*Build the new element*/
	newElem = (ELEMENT *)malloc(sizeof(ELEMENT));
	newElem->d=G;
	newElem->next=NULL;

	newElem->next=(*p_list);
	*p_list = newElem;

	return 1;
}

int isEmpty(LINK list)
{
	return (list == NULL);
}

int removeHead(LINK *list_p)
{
	if (*list_p == NULL)
		return 0;/*LIst is already empty*/
	(*list_p) = (*list_p)->next;
	return 1;
}
